import { performance } from 'perf_hooks';
import {approve, depositRedPackBuildTx, sendTX} from './client/bcos/BcosClient.js';


const concurrency = 1; // 并发数
const iterations = 1; // 测试次数

const fromAddress = '0xA55F5719A18af522085ee80A3f0e4286EeE2f231'; // 设置参数
const privateKey = '0xa53a0eeace02249d95f7024fee56ca68a229641a6c497fdcb098e717ed1bcbe8'; // 设置参数
const assetAddress = '0x30610fc6d2cdb887d2e70d0371218081348ee0ef'
const redPackAddress = '0x99296c983e6f4c05615f3ed1401a25b51fd3a3e1'; // 设置参数
const userAddress = '0x391ded7cfd9da82fc4191f517217f1edbd7a4aca'
const asset = {"assetConfig": {"chainID": "wbbcoccnode", "groupID": "group0", "rechargeWithdrawContractAddress": "0x028d27e08e09a5f612c90a84967189c7bcf2c4b4"}, "assetIcon": "", "assetName": "元豆", "assetStatus": 1, "assetSymbol": "yuandou", "assetType": "20", "contractAddress": "0x30610fc6d2cdb887d2e70d0371218081348ee0ef", "networkName": "main"}; // 设置参数


const amount = "1"; // 设置参数
approve(fromAddress,privateKey,assetAddress,redPackAddress,amount,asset);

const signedTxDataArray = [];

// 循环生成签名
async function generateSignedTxData() {
  for (let i = 0; i < concurrency * iterations; i++) {
    try {
      const amount1 = "1"; // 设置参数
      const signedTxData = await depositRedPackBuildTx(userAddress,privateKey, redPackAddress, amount1, asset);
      signedTxDataArray.push(signedTxData);
      console.log(`Signed transaction data ${i + 1} generated successfully.`);
    } catch (error) {
      console.error(`Error generating signed transaction data ${i + 1}:`, error);
    }
  }
}

const startTime = performance.now();

let completedRequests = 0;
let totalRequestTime = 0;

async function runConcurrentDepositRedPackRequests() {
  const promises = [];
  for (let i = 0; i < concurrency; i++) {
    promises.push(runSingleDepositRedPack(i));
  }
  await Promise.all(promises);
}

async function runSingleDepositRedPack(index) {
  for (let i = index * iterations  ; i < index * iterations + iterations; i++) {
    try {
      const signedTxData = signedTxDataArray[i];
      // 调用要测试的方法
      const startRequestTime = performance.now();
      sendTX(fromAddress, signedTxData, asset).then(() => {
        const endRequestTime = performance.now();
        const requestTime = endRequestTime - startRequestTime;
        console.log("sendTx = ", requestTime)
        totalRequestTime += requestTime;
        console.log(`Request ${index + 1} - Iteration ${i + 1} successful. Result:`);
        completedRequests++;

        if(completedRequests === concurrency * iterations){
          const endTime = performance.now();
          const totalTime = endTime - startTime;
          const tps = completedRequests / (totalTime / 1000);
          const averageRequestTime = totalRequestTime / completedRequests;
          console.log(`All requests completed in ${totalTime} milliseconds.`);
          console.log(`Average request time: ${averageRequestTime} milliseconds.`);
          console.log(`TPS: ${tps}`);
        }

      });
    } catch (error) {
      console.error(`Request ${index + 1} - Iteration ${i + 1} failed:`, error);
    }
  }
}

// 调用函数生成签名数据
generateSignedTxData().then(() => {
  console.log('All signed transaction data generated.');
 
 

  const startTime = performance.now();
  runConcurrentDepositRedPackRequests().then(() => {
    // const endTime = performance.now();
    // const totalTime = endTime - startTime;
    // const tps = completedRequests / (totalTime / 1000);
    // const averageRequestTime = totalRequestTime / completedRequests;
    // console.log(`All requests completed in ${totalTime} milliseconds.`);
    // console.log(`Average request time: ${averageRequestTime} milliseconds.`);
    // console.log(`TPS: ${tps}`);
  });
  // 这里可以开始压测或者进行其他操作
}).catch(error => {
  console.error('Error generating signed transaction data:', error);
});



